import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:star_author/config/app.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/model/backflow.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/icon.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/views/products/bidder_goods_detail_page/widgets/bidder_report_bottom_sheet.dart';
import 'package:star_author/views/products/bidder_goods_detail_page/widgets/bidder_tips_dialog.dart';
import 'package:star_author/views/products/bidder_goods_detail_page/widgets/comment_list_item.dart';
import 'package:star_author/widgets/empty_view/h_empty_view.dart';

class CommentListWidget extends StatefulWidget {
  final int remaining;
  final String? status;
  final String tenderPrice;
  final String strategy;
  final String rateForDeducting;
  final bool isEvaluated;
  final BackflowModel? backflowModel;
  final bool isMine;
  final Widget? immediateCard;
  final List? comments;
  String body;
  String title;

  CommentListWidget({
    Key? key,
    this.immediateCard,
    this.rateForDeducting: "",
    this.backflowModel,
    this.tenderPrice: "0",
    this.status,
    this.comments,
    required this.remaining,
    required this.body,
    required this.title,
    required this.strategy,
    required this.isEvaluated,
    required this.isMine,
  });

  @override
  State<CommentListWidget> createState() => _CommentListWidgetState();
}

class _CommentListWidgetState extends State<CommentListWidget> {
  List<dynamic> _list = [];

  Map<String, dynamic>? _best;

  bool isShowValidList = false;

  List<dynamic> _validList = [];

  List<String> bestStatus = [
    'waitconfirm',
    'onsale',
    'sold',
    'finished',
    'approved',
    'wait_pay',
  ];

  BackflowModel? backflowModel;

  @override
  void didUpdateWidget(covariant CommentListWidget oldWidget) {
    if (oldWidget.comments != widget.comments ||
        oldWidget.backflowModel != widget.backflowModel) {
      initWidget();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    super.initState();
    initWidget();
  }

  void initWidget() {
    backflowModel = widget.backflowModel;
    _list = [];
    _validList = [];
    _best = null;
    if (widget.comments != null && widget.comments!.length > 0) {
      if (bestStatus.contains(widget.status)) {
        _best = widget.comments![0];
        _list = widget.comments!.sublist(1);
        LogUtil.v('initWidget---1--${_list.length} - ${_validList.length}');
      } else {
        _list = widget.comments!;
        LogUtil.v('initWidget---2--${_list.length} - ${_validList.length}');
      }

      //货主端判断
      if (widget.isMine) {
        int isValidIndex =
            _list.indexWhere((element) => !(element['is_valid'] ?? false));
        if (isValidIndex != -1) {
          List tempList = _list;
          _list = _list.sublist(0, isValidIndex);
          _validList = tempList.sublist(isValidIndex);
          LogUtil.v('initWidget---3--${_list.length} - ${_validList.length}');
        }
      }
    }
    setState(() {});
  }

  List<Widget> render() {
    if (widget.status != null) {
      if (_list.length > 0 || _best != null || _validList.length > 0) {
        return [
          if (widget.immediateCard != null) widget.immediateCard!,
          if (_best != null)
            CommentListItemWidget(
              best: true,
              item: _best!,
              isEvaluated: widget.isEvaluated,
              tenderPrice: widget.tenderPrice,
              rateForDeducting: widget.rateForDeducting,
              status: widget.status ?? '',
              isMine: widget.isMine,
              index: 0,
            ),
          ListView.builder(
            itemBuilder: (ctx, index) {
              return CommentListItemWidget(
                item: _list[index],
                isEvaluated: widget.isEvaluated,
                tenderPrice: widget.tenderPrice,
                rateForDeducting: widget.rateForDeducting,
                status: widget.status ?? '',
                isMine: widget.isMine,
                index: _best != null ? index + 1 : index,
              );
            },
            itemCount: _list.length,
            shrinkWrap: true,
            primary: false,
            padding: EdgeInsets.zero,
          ),
          if (!isShowValidList && _validList.length > 0) foldWidget(),
          if (isShowValidList)
            ListView.builder(
              itemBuilder: (ctx, index) {
                return CommentListItemWidget(
                  item: _validList[index],
                  isEvaluated: widget.isEvaluated,
                  tenderPrice: widget.tenderPrice,
                  rateForDeducting: widget.rateForDeducting,
                  status: widget.status ?? '',
                  isMine: widget.isMine,
                  index: _best != null ? index + 1 : index,
                );
              },
              itemCount: _validList.length,
              shrinkWrap: true,
              primary: false,
              padding: EdgeInsets.zero,
            ),
        ];
      } else {
        return [emptyCommentWidget()];
      }
    } else {
      return [];
    }
  }

  Widget foldWidget() {
    return Container(
      padding: EdgeInsets.only(top: 18.w),
      alignment: Alignment.center,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          isShowValidList = true;
          setState(() {});
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '已折叠${_validList.length}个无效出价',
              style: TextStyle(
                color: UIConstant.color99,
                fontSize: 12.sp,
              ),
            ),
            HEmptyView(3.w),
            Image.asset(
              'images/ic_arrow_down.png',
              width: 10.w,
            ),
          ],
        ),
      ),
    );
  }

  Widget emptyCommentWidget({
    String tips: "正在竞拍出价中，敬请耐心等待",
  }) {
    return Container(
      width: double.infinity,
      margin: GetPadding.only(top: 9.w),
      child: Column(
        children: [
          Icon(
            IconFont.shalou,
            color: ColorConf.lightGray,
            size: 20.w,
          ),
          Container(
            margin: GetPadding.only(top: 10.w),
            child: Text(
              '正在${App.evaluation_text}出价中，敬请耐心等待',
              style: TextStyle(
                color: ColorConf.lightGray,
                fontSize: 12.sp,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildReportButton() {
    Map<String, Widget> viewMap = {
      'true': GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          BidderReportBottomSheetHandler.showSheet(
              backflowModel?.originalData ?? {}, () {
            HttpUtil.commonRequest(
              Get.context!,
              '/api/v1/backflows/${widget.backflowModel?.id}',
              isLoading: true,
            ).then((value) {
              Map<String, dynamic> _data = value.data ?? {};
              backflowModel = BackflowModel(_data);
              if (mounted) setState(() {});
            });
          });
        },
        child: Row(
          children: [
            Image.asset(
              'images/ic_bidder_report_lt.png',
              width: 12.w,
              height: 12.w,
            ),
            HEmptyView(4.w),
            Text(
              '异常举报',
              style: TextStyle(
                color: rgba(153, 153, 153, 1),
                fontSize: 12.sp,
              ),
            )
          ],
        ),
      ),
      'false': Container(),
      'has_reported': Text(
        '已举报',
        style: TextStyle(
          color: rgba(204, 204, 204, 1),
          fontSize: 12.sp,
        ),
      ),
    };

    return viewMap[backflowModel?.originalData['may_report'] ?? 'false'] ??
        Container();
  }

  Widget buildIcon() {
    if ((widget.backflowModel?.wait_at?.isNotEmpty ?? false)) {
      if ((widget.backflowModel?.opening_insight ?? "").isEmpty) {
        return Container();
      }
      return Container(
        height: 22.w,
        margin: EdgeInsets.only(left: 8.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.w),
        ),
        child: Image.asset(
          RoucesUtil.getAssets('ic_ower_stop'),
          width: 80.w,
          height: 20.w,
        ),
      );
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: GetPadding.only(top: 18.w, bottom: 10.w),
      color: ColorConf.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //竞拍小提示
          if (widget.body.isNotEmpty)
            GestureDetector(
              child: Container(
                height: 40.w,
                width: Get.width,
                decoration: BoxDecoration(
                  color: rgba(249, 248, 247, 1),
                  borderRadius: BorderRadius.circular(4.w),
                ),
                padding: EdgeInsets.symmetric(
                  horizontal: 12.w,
                ),
                margin: EdgeInsets.only(
                  bottom: 12.w,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        RoucesUtil.getAssetsIcon('ic_bidder_tips_lt', 18),
                        SizedBox(
                          width: 6.w,
                        ),
                        Text(
                          widget.title,
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: rgba(139, 87, 42, 1),
                          ),
                        )
                      ],
                    ),
                    Image(
                      image: AssetImage('images/lt_common/right_arrow.png'),
                      width: 6.w,
                    ),
                  ],
                ),
              ),
              onTap: () {
                Get.bottomSheet(
                  BidderTipsDialog(
                    title: widget.title,
                    body: widget.body,
                  ),
                  isScrollControlled: true,
                  persistent: false,
                );
              },
            ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                '${App.evaluation_text}实况 ${(widget.backflowModel?.tendersCount ?? 0) > 0 ? "(${widget.backflowModel?.tendersCount})" : ""}',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold,
                  color: ColorConf.normal,
                ),
                textAlign: TextAlign.center,
              ),
              buildIcon(),
              Expanded(
                child: Container(),
                flex: 1,
              ),
              buildReportButton(),
            ],
          ),
          ...render()
        ],
      ),
    );
  }
}
